using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;
using System.Text.RegularExpressions;

/// <summary>
/// Summary description for Interceptor
/// </summary>  IHttpModule
/// 

namespace Calypso
{
    public class Interceptor : System.Web.IHttpModule
    {
        private  string sXmlFileName = "";
        public void Dispose() { }

        public Interceptor()
        {

        }

        public void Init(HttpApplication context)
        {
//          context.BeginRequest += new EventHandler(context_BeginRequest);
           // context.EndRequest += new EventHandler(context_EndRequest);
            //context.BeginRequest += new EventHandler(context_BeginRequestFindPath);
            context.BeginRequest += new EventHandler(context_BeginRequestFindPath);
        }

        void context_BeginRequestFindPath(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            sXmlFileName = app.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "calypso-config.xml";
             XPathDocument xDoc = new XPathDocument(sXmlFileName);
            XPathNavigator xNavigator = xDoc.CreateNavigator();
          
            string sScriptPath = app.Context.Request.ServerVariables["SCRIPT_NAME"];           
            XPathNodeIterator iter = xNavigator.Select("/calypso/views/page-view/page");
             sScriptPath = Regex.Replace(sScriptPath, "/Test1/", "");

            //System.Diagnostics.Debug.Print("\nsScriptPath mod: " + sScriptPath);
            //Check if the pattern matches
          
                while (iter.MoveNext())
                {
                    string sViewRegex = "";                    
                   // System.Diagnostics.Debug.Print("\nview: " + iter.Current.Value);
                    XPathNodeIterator iterRewrite = iter.Current.Select("./rewrite");
                    string sLocationToForward = "";
                    if (iterRewrite.MoveNext())
                    {                      
                        sViewRegex = iterRewrite.Current.Value;
                        sLocationToForward = iter.Current.GetAttribute("location", "");
                    }

                    bool isMatchFound = false;
                    //Start of rewriting of the URL
                    Regex oRegex = new Regex(@sViewRegex, RegexOptions.IgnoreCase);
                    MatchCollection MatchList = oRegex.Matches(sScriptPath);

                    if (MatchList.Count > 0)
                    {
                       Match FirstMatch = MatchList[0];
                       isMatchFound = true;
                       sLocationToForward = FirstMatch.Result(sLocationToForward);
                    }

                    if (isMatchFound)
                    {
                        try
                        {
                            //Check for master page
                            XPathNodeIterator iterMasterPage = iter.Current.Select("./view-handlers/masterpage");
                            string sMasterPage = "";
                            if (iterMasterPage.MoveNext())
                            {
                                string sMasterPageAliasName = "";
                                sMasterPageAliasName = iterMasterPage.Current.GetAttribute("name", "");
                               // Debug.Print("sMasterPageAliasName=" + sMasterPageAliasName);
                                string role = "default";
                                XPathNodeIterator iterMasterPageAlias = xNavigator.Select("/calypso/masterpages/allias[@key='" + sMasterPageAliasName + "' and @role='" + role + "']");
                                if (iterMasterPageAlias.MoveNext())
                                {
                                    sMasterPage = iterMasterPageAlias.Current.GetAttribute("page", "");
                                }
                             }                        
                             app.Context.Application.Set("master-template", sMasterPage);
                             app.Context.Server.Transfer(sLocationToForward, true);
                        }
                        catch (System.Exception ex)
                        {
                            // app.Context.Response.Write(ex.StackTrace);
                            // app.Context.Response.Write(ex.ToString());
                        }
                  
                    }
                }
            }

         /*
          try
            {
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
          */
        
        /*
        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
             
            app.Context.Response.Write("Begin Request ");

            string path = app.Context.Request.ServerVariables["SCRIPT_NAME"];
            Debug.Print("path=" + path);
            if (app.Request.RequestType.ToString().Equals("POST"))
            {
                System.Diagnostics.Debug.Print(" Redirecting ");

                System.Text.StringBuilder displayValues = new System.Text.StringBuilder();
                System.Collections.Specialized.NameValueCollection postedValues = app.Request.Form;

                String nextKey;
                for (int i = 0; i < postedValues.AllKeys.Length - 1; i++)
                {
                    nextKey = postedValues.AllKeys[i];
                    if (nextKey.Substring(0, 2) != "__")
                    {
                        displayValues.Append("<br>");
                        displayValues.Append(nextKey);
                        displayValues.Append(" = ");
                        displayValues.Append(postedValues[i]);
                    }
                }

                app.Context.Response.Write("Original Data > <br>" + displayValues.ToString());

                HttpFileCollection uploadFilCol = app.Context.Request.Files;
                app.Context.Response.Write("uploadFilCol.Count  > " + uploadFilCol.Count);


                try
                {
                    //      app.Context.Server.Transfer("~/page_1.aspx", true);
                    //  app.Server.Execute("~/page_1.aspx", true);

                }
                catch (System.Exception ex)
                {
                    app.Context.Response.Write(ex.StackTrace);
                    // app.Context.Response.Write(ex.ToString());
                }


            }
        
        } */
    }
}